package com.dlwx.parttimetalent.fragment;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.dlwx.parttimetalent.R;
import com.dlwx.parttimetalent.bean.BaseBean;
import com.dlwx.parttimetalent.bean.PurseBean;
import com.dlwx.parttimetalent.comm.Constant;
import com.dlwx.parttimetalent.comm.Http;
import com.dlwx.parttimetalent.service.MyService;
import com.dlwx.parttimetalent.ui.AboutUsActivity;
import com.dlwx.parttimetalent.ui.CertificateActivity;
import com.dlwx.parttimetalent.ui.DaRenActivity;
import com.dlwx.parttimetalent.ui.HelpActivity;
import com.dlwx.parttimetalent.ui.LoginActivity;
import com.dlwx.parttimetalent.ui.MyOrderActivity;
import com.dlwx.parttimetalent.ui.SettingActivity;
import com.dlwx.parttimetalent.ui.TuiGuangActivity;
import com.dlwx.parttimetalent.ui.WalletActivity;
import com.dlwx.parttimetalent.utils.CacheManager;
import com.dlwx.parttimetalent.utils.CallPhoneUtil;
import com.dlwx.parttimetalent.utils.DealResult;
import com.dlwx.parttimetalent.utils.DialogUtils;
import com.dlwx.parttimetalent.utils.HxUtils;
import com.dlwx.parttimetalent.utils.LogUtils;
import com.dlwx.parttimetalent.utils.OkgoUtil;
import com.dlwx.parttimetalent.utils.SPUtils;
import com.dlwx.parttimetalent.utils.ToastUtils;
import com.dlwx.parttimetalent.wxapi.QQUtiles;
import com.flyco.dialog.listener.OnBtnClickL;
import com.flyco.dialog.widget.NormalDialog;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.tencent.bugly.beta.Beta;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import cn.jpush.android.api.JPushInterface;
import de.hdodenhof.circleimageview.CircleImageView;

public class FourFragment extends Fragment {
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    @BindView(R.id.image_header)
    CircleImageView imageHeader;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_signature)
    EditText tvSignature;
    @BindView(R.id.tv_money)
    TextView tvMoney;
    @BindView(R.id.tv_order_income)
    TextView tvOrderIncome;
    @BindView(R.id.tv_tuiguang_income)
    TextView tvTuiguangIncome;
    @BindView(R.id.ll_wallet)
    RelativeLayout llWallet;
    @BindView(R.id.ll_renzheng)
    RelativeLayout llRenzheng;
    @BindView(R.id.ll_daren)
    RelativeLayout llDaren;
    @BindView(R.id.ll_tuiguang)
    RelativeLayout llTuiguang;
    @BindView(R.id.rl_kefu)
    RelativeLayout rlKefu;
    @BindView(R.id.rl_help)
    RelativeLayout rlHelp;
    @BindView(R.id.rl_us)
    RelativeLayout rlUs;
    @BindView(R.id.rl_clear)
    RelativeLayout rlClear;
    @BindView(R.id.rl_update)
    RelativeLayout rlUpdate;
    @BindView(R.id.tv_exit)
    TextView tvExit;
    Unbinder unbinder;
    @BindView(R.id.image_setting)
    ImageView imageSetting;
    @BindView(R.id.image0)
    ImageView image0;
    @BindView(R.id.tv_wallet)
    TextView tvWallet;
    @BindView(R.id.image1)
    ImageView image1;
    @BindView(R.id.tv_renzheng)
    TextView tvRenzheng;
    @BindView(R.id.image2)
    ImageView image2;
    @BindView(R.id.tv_daren)
    TextView tvDaren;
    @BindView(R.id.image3)
    ImageView image3;
    @BindView(R.id.tv_tuiguang)
    TextView tvTuiguang;
    @BindView(R.id.rl_order)
    RelativeLayout rlOrder;
    @BindView(R.id.image_pen)
    ImageView imagePen;

    private String mParam1;
    private String mParam2;
    private OnFragmentInteractionListener mListener;
    private QQUtiles qqUtils;
    private NormalDialog dialog1;
    protected InputMethodManager inputMethodManager;
    private String rmb;


    public FourFragment() {
    }

    public static FourFragment newInstance(String param1, String param2) {
        FourFragment fragment = new FourFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        inputMethodManager = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        rmb=getString(R.string.rmb);
        qqUtils = new QQUtiles();
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_four, container, false);
        unbinder = ButterKnife.bind(this, view);

        getWalletInfo();
        return view;
    }

    private void saveSign() {
        String sign=tvSignature.getText().toString();
        if(TextUtils.isEmpty(sign)){
            ToastUtils.toastForShort(getActivity(),"签名不能为空");return;
        }

        OkgoUtil.post(Http.setuUserInfo, getActivity())
                .params("infoName","usersign")
                .params("values",sign)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        BaseBean parentBean = DealResult.getInstance().dealDatas(getActivity(), response, new TypeToken<BaseBean>() {
                        }.getType());
                        if (parentBean == null) {
                            return;
                        }
                        int code = parentBean.getCode();
                        if (code == Constant.SUCESS) {
                            ToastUtils.toastForShort(getActivity(),parentBean.getResult());
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        ToastUtils.toastForShort(getActivity(), getString(R.string.bad_net));
                    }
                });
    }

    private void setDatas(PurseBean.BodyBean bean) {
        SPUtils.put(getActivity(),Constant.KEFU_PHONE,bean.getTelphone());
        if(isVisible()){
            tvMoney.setText(rmb + bean.getAccountTotal());
            tvOrderIncome.setText(rmb+ bean.getWagesTotal());
            tvTuiguangIncome.setText(rmb+ bean.getExtendTotal());
            tvSignature.setText(bean.getUsersign());
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        initView();
    }

    private void initView() {
        String headUrl = (String) SPUtils.get(getActivity(), Constant.HEAD_URL, "");
        String nickName = (String) SPUtils.get(getActivity(), Constant.NICK_NAME, "");
        Glide.with(getActivity()).load(headUrl).into(imageHeader);
        tvName.setText(nickName);
        tvSignature.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE) {
                    hideSoftKeyboard();
                    saveSign();
                    LogUtils.d("IME_ACTION_DONE");
                }
                return true;
            }
        });
    }
    private void getWalletInfo() {
        OkgoUtil.post(Http.MyPurse, getActivity())
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        PurseBean parentBean = DealResult.getInstance().dealDatas(getActivity(), response, new TypeToken<PurseBean>() {
                        }.getType());
                        if (parentBean == null) {
                            return;
                        }
                        int code = parentBean.getCode();
                        if (code == Constant.SUCESS) {
                            setDatas(parentBean.getBody());
                        }
//                        ToastUtils.toastForShort(getActivity(),parentBean.getResult());
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        ToastUtils.toastForShort(getActivity(), getString(R.string.bad_net));
                    }
                });
    }

    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
//            throw new RuntimeException(context.toString() + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }
    private boolean isEdit=false;
    @OnClick({R.id.tv_tuiguang_income, R.id.image_setting,R.id.image_pen
            , R.id.ll_wallet, R.id.ll_renzheng, R.id.ll_daren, R.id.ll_tuiguang
            , R.id.rl_kefu, R.id.rl_help, R.id.rl_us, R.id.rl_clear, R.id.rl_update, R.id.tv_exit, R.id.rl_order
    ,R.id.image_header})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_tuiguang_income:
                break;
            case R.id.image_header:
                startActivity(new Intent(getActivity(), SettingActivity.class));
                break;
            case R.id.image_pen:
//                if(isEdit){
//                    tvSignature.setCursorVisible(false);
//                    isEdit=false;
//                }else{
//                    tvSignature.setCursorVisible(true);
//                    isEdit=true;
//                }
                saveSign();
                break;
            case R.id.ll_wallet:
                startActivity(new Intent(getActivity(), WalletActivity.class));
                break;
            case R.id.ll_renzheng:
                startActivity(new Intent(getActivity(), CertificateActivity.class));
                break;
            case R.id.ll_daren:
                startActivity(new Intent(getActivity(), DaRenActivity.class));
                break;
            case R.id.ll_tuiguang:
                startActivity(new Intent(getActivity(), TuiGuangActivity.class));
                break;
            case R.id.rl_kefu:
                final NormalDialog dialog = DialogUtils.getDialogMiddle(getActivity(), "", "拨打客服电话");
                dialog.setOnBtnClickL(new OnBtnClickL() {
                                          @Override
                                          public void onBtnClick() {
                                              dialog.dismiss();
                                          }
                                      }, new OnBtnClickL() {
                                          @Override
                                          public void onBtnClick() {
                                              dialog.dismiss();
                                              String phone= (String) SPUtils.get(getActivity(),Constant.KEFU_PHONE,"");
                                              CallPhoneUtil.call(getActivity(),phone);
                                          }
                                      }
                );
                break;
            case R.id.rl_help:
                startActivity(new Intent(getActivity(), HelpActivity.class));
                break;
            case R.id.rl_us:
                startActivity(new Intent(getActivity(), AboutUsActivity.class));
                break;
            case R.id.rl_clear:
                final NormalDialog dialogCache = DialogUtils.getDialogMiddle(getActivity(), "", "将删除所有缓存的图片和视频，删除后不可恢复，请在交易完成后操作");
                dialogCache.setOnBtnClickL(new OnBtnClickL() {
                                               @Override
                                               public void onBtnClick() {
                                                   dialogCache.dismiss();
                                               }
                                           }, new OnBtnClickL() {
                                               @Override
                                               public void onBtnClick() {
                                                   dialogCache.dismiss();
                                                   CacheManager.clearAllCache(getActivity());
                                                   ToastUtils.toastForShort(getActivity(), "清楚缓存成功！");
                                               }
                                           }
                );
                break;
            case R.id.rl_update:
                Beta.checkUpgrade();
//                ToastUtils.toastForShort(getActivity(), "目前没有新版本可更新！");
                break;
            case R.id.tv_exit:
                dialog1 = DialogUtils.getLoginOut(getActivity(), " ", "您真的忍心离开约神，要不要再看看~~~");
                dialog1.setOnBtnClickL(new OnBtnClickL() {
                                           @Override
                                           public void onBtnClick() {
                                               loginOut();
                                               dialog1.dismiss();
                                           }
                                       }, new OnBtnClickL() {
                                           @Override
                                           public void onBtnClick() {
                                               dialog1.dismiss();

                                           }
                                       }
                );
                break;
            case R.id.image_setting:
                startActivity(new Intent(getActivity(), SettingActivity.class));
//                startActivity(new Intent(getActivity(), EvaluateActivity.class));
//                SoundPlayer.play(getActivity());
                 break;
            case R.id.rl_order:
                startActivity(new Intent(getActivity(), MyOrderActivity.class));
                break;
        }
    }

    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (dialog1 != null) {
            dialog1.dismiss();
            dialog1 = null;
        }

    }

    protected void hideSoftKeyboard() {
        if (getActivity().getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
            if (getActivity().getCurrentFocus() != null)
                inputMethodManager.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(),
                        InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    private void loginOut(){
        OkgoUtil.post(Http.UserOut, getActivity())
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        BaseBean parentBean = DealResult.getInstance().dealDatas(getActivity(), response, new TypeToken<BaseBean>() {
                        }.getType());
                        if (parentBean == null) {
                            return;
                        }
                        int code = parentBean.getCode();
                        if (code == Constant.SUCESS) {
                            SPUtils.clear(getActivity());
                            SPUtils.put(getActivity(), Constant.isLogin, false);
                            SPUtils.put(getActivity(), Constant.First_START, false);
                            JPushInterface.cleanTags(getActivity(), 0);
//                                               JPushInterface.deleteTags();
                            qqUtils.logout(getActivity());
                            HxUtils.loginOut();
                            Intent stopIntent = new Intent(getActivity(), MyService.class);
                            getActivity().stopService(stopIntent);
                            Intent i = new Intent(getActivity(), LoginActivity.class);
                            i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                            startActivity(i);
                        }
                    }
                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        ToastUtils.toastForShort(getActivity(), getString(R.string.bad_net));
                    }
                });
    }
}
